#include "TextureManager.h"

TextureManager* TextureManager::s_pInstance = 0;

TextureManager::TextureManager()
{
	// do nothing
}

TextureManager::~TextureManager()
{
	//do nothing
}

void TextureManager::add(Sprite _sprite, SDL_Renderer* pRenderer)
{
	m_sprite = _sprite;
	string fileName = m_sprite.getNameTexture();

	m_textureSprite = IMG_LoadTexture(pRenderer, fileName.c_str());

	m_textureMap[fileName] = m_textureSprite;
}

bool TextureManager::load(string fileName, string id, SDL_Renderer* pRenderer)
{
	SDL_Surface* pTempSurface = IMG_Load(fileName.c_str()); 

	SDL_Texture* pTexture = SDL_CreateTextureFromSurface(pRenderer, pTempSurface); 
	SDL_FreeSurface(pTempSurface); 

	m_textureMap[id] = pTexture; 

	return true;
}

void TextureManager::draw(std::string id, int x, int y, int width, int height, SDL_Renderer* pRenderer,
	SDL_RendererFlip flip)
{
	SDL_Rect srcRect; 
	SDL_Rect destRect; 

	destRect = { x, y, width, height };

	SDL_RenderCopyEx(pRenderer, m_textureMap[id], NULL, &destRect, 0, 0, flip); 
}

void TextureManager::drawParallax(Sprite _sprite, int &_idSprite, SDL_Renderer* pRenderer,
	SDL_RendererFlip flip)
{
	m_sprite = _sprite;

	int x = m_sprite.getSpriteImage()[_idSprite].image_x;
	int y = m_sprite.getSpriteImage()[_idSprite].image_y;
	int w = m_sprite.getSpriteImage()[_idSprite].image_w;
	int h = m_sprite.getSpriteImage()[_idSprite].image_h;

	int _x = m_sprite.getSpriteImage()[_idSprite].image_possition_x;
	int _y = m_sprite.getSpriteImage()[_idSprite].image_possition_y;
	int _w = m_sprite.getSpriteImage()[_idSprite].image_possition_width;
	int _h = m_sprite.getSpriteImage()[_idSprite].image_possition_height;
	SDL_Rect srcRect;
	SDL_Rect destRect;

	srcRect = {x, y , w, h };
	destRect = { _x, _y, _w, _h};
	string id = m_sprite.getNameTexture();

	SDL_RenderCopyEx(pRenderer, m_textureMap[id], &srcRect, &destRect, 0, 0, flip);
}

void TextureManager::drawFrame(std::string id, int x, int y, int width, int height,
	int currentRow, int currentFrame, SDL_Renderer *pRenderer, SDL_RendererFlip flip)
{
	SDL_Rect srcRect; //source rectangle
	SDL_Rect destRect; //destination rectangle

	srcRect.x = width * currentFrame;
	srcRect.y = height * (currentRow - 1);
	srcRect.w = destRect.w = width;
	srcRect.h = destRect.h = height;
	destRect.x = x;
	destRect.y = y;

	SDL_RenderCopyEx(pRenderer, m_textureMap[id], &srcRect, &destRect, 0, 0, flip);
	//Load current frame on the buffer game.
}

void TextureManager::clearFromTextureMap(string id)
{
	m_textureMap.erase(id);
}

map<string, SDL_Texture*> TextureManager::GetBoundingBox()
{
	return m_textureMap;
}